package com.yc.service.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;

/**
 * 微信服务
 * 
 * @author 
 *
 */
public class WeixinService {

	private String corpid = "wx40642aaea77f649a";
	private String corpsecret = "OLYUyA3hCMZsbNHnDcxxZ6G5nVaYqbLDBpi1cuEQ3nMEDnrBaqU_-OdY0Td2zplg";

	private static Integer expires_in;
	private static String accessToken;
	private static long validateTime;

	private WeixinService() {
	}

	private static final WeixinService wsInstance = new WeixinService();

	public static WeixinService getInstance() {
		if (wsInstance == null)
			return new WeixinService();
		return wsInstance;
	}

	/**
	 * https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&corpsecret=secrect
	 * 
	 * @return
	 */
	private String getAccessToken() {

		if (expires_in != null && expires_in != 0 && accessToken != null
				&& !"".equals(accessToken) && validateTime != 0) {
			// 判断有效时间 是否超过2小时
			java.util.Date end = new java.util.Date();
			java.util.Date start = new java.util.Date(validateTime);
			if ((end.getTime() - start.getTime()) / 1000 / 3600 >= 1) {// 1个小时取一次，防止过期，一天最多200次调用
				String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="
						+ corpid + "&corpsecret=" + corpsecret;
				String responseBody = getWebContentByGet(url, "utf-8");
				JSONObject jsonObj = JSONObject.parseObject(responseBody);
				accessToken = (String) jsonObj.get("access_token");
				expires_in = (Integer) jsonObj.get("expires_in");
				validateTime = new java.util.Date().getTime();
				System.out
						.println("getAccessToken accessToken==" + accessToken);
			} else {
				System.out.println("get already exist Token==" + accessToken);
				return accessToken;
			}
		} else {
			String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="
					+ corpid + "&corpsecret=" + corpsecret;
			String responseBody = getWebContentByGet(url, "utf-8");
			JSONObject jsonObj = JSONObject.parseObject(responseBody);
			accessToken = (String) jsonObj.get("access_token");
			expires_in = (Integer) jsonObj.get("expires_in");
			validateTime = new java.util.Date().getTime();
			System.out.println("getAccessToken accessToken==" + accessToken);
		}

		return accessToken;
	}

	/**
	 * 返回BASE64后的Userid
	 * https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token
	 * =ACCESS_TOKEN&code=CODE
	 * {"UserId":"zcp","DeviceId":"79f67d89c998cf33b410c12377e61790"}
	 * 
	 * @return
	 */
	public String getBase64Userid(String code) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="
				+ getAccessToken() + "&code=" + code;
		String responseBody = getWebContentByGet(url, "utf-8");
		System.out.println(responseBody);
		JSONObject jsonObj = JSONObject.parseObject(responseBody);
		String userid = (String) jsonObj.get("UserId");
		System.out.println("getBase64Userid userid==" + userid);
		if (userid == null || "".equals(userid))
			return null;
		return getBase64(userid);
	}

	/**
	 * 获得请求返回的内容
	 * 
	 * @param url
	 * @param charset
	 * @return
	 */
	private String getWebContentByGet(String url, String charset) {
		HttpClient client = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		StringBuilder sb = new StringBuilder();
		try {
			// 状态码
			int statusCode = client.executeMethod(getMethod);
			if (statusCode == HttpStatus.SC_OK) {
				// 获得HTML文本
				BufferedReader bf = new BufferedReader(new InputStreamReader(
						getMethod.getResponseBodyAsStream(), charset));
				String line = null;
				while ((line = bf.readLine()) != null) {
					sb.append(line).append("\r\n");
				}
				bf.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return sb.toString();
	}

	/**
	 * 获得网页中的所有HTML内容
	 * 
	 * @param url
	 * @param mapData
	 *            :传递的参数
	 * @param charset
	 * @return
	 */
	private String getWebContentByPost(String url, String content) {
		org.apache.http.client.HttpClient client = new DefaultHttpClient();
		HttpPost postMethod = new HttpPost(url);

		// 建立一个NameValuePair数组，用于存储欲传送的参数
		postMethod.addHeader("Content-type", "application/json; charset=utf-8");
		postMethod.setHeader("Accept", "application/json");
		postMethod
				.setEntity(new StringEntity(content, Charset.forName("UTF-8")));

		HttpResponse response = null;
		try {
			response = client.execute(postMethod);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
			}

			// Read the response body
			return EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}

		return null;
	}

	// 加密
	private String getBase64(String str) {
		byte[] b = null;
		String s = null;
		try {
			b = str.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
		if (b != null) {
			s = new BASE64Encoder().encode(b);
		}
		return s;
	}

	public void sendNews(String receiver ,String title,String desc,String openURL) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
				+ getAccessToken();
		String jsoncontent = "{\"touser\":\""+receiver+"\",\"msgtype\":\"news\",\"agentid\":37,\"news\":{\"articles\":[{\"title\":\""+title+"\",\"url\":\""+openURL+"\",\"description\": \""+desc+"\"}]}}";
		String response  = getWebContentByPost(url, jsoncontent);
		System.out.println("WeixinService=="+jsoncontent+"response=="+response);
	}
	
	public void sendPCNews(String receiver ,String title,String desc,String openURL) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
				+ getAccessToken();
		String jsoncontent = "{\"touser\":\""+receiver+"\",\"msgtype\":\"news\",\"agentid\":41,\"news\":{\"articles\":[{\"title\":\""+title+"\",\"url\":\""+openURL+"\",\"description\": \""+desc+"\"}]}}";
		String response  = getWebContentByPost(url, jsoncontent);
		System.out.println("WeixinService=="+jsoncontent+"response=="+response);
	}
	
	
	public void sendText(String receiver ,String content) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
				+ getAccessToken();
		String jsoncontent = "{\"touser\":\""+receiver+"\",\"msgtype\":\"text\",\"agentid\":40,\"text\":{\"content\":\""+content+"\"}, \"safe\":0}";
		String response  = getWebContentByPost(url, jsoncontent);
		System.out.println("WeixinService=="+jsoncontent+"response=="+response);
	}
	
}
